import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {connect} from 'react-redux'
import {AtSearchBar} from 'taro-ui'
import {View, Image, ScrollView, Block} from '@tarojs/components'
import {Good, CityLocation, SubCategory} from '../../utils/server.interface'
import {http} from '../../utils/http'
import {
  BANNER_SEARCH_TYPE,
  CATEGORY_SCENIC_PAGE,
  CATEGORY_TOURIST_PAGE,
  HOTEL_PRODUCT, IDENTITY_IS_SELLER,
  LIST_CATEGORY,
  RESOURCE_URL, SCAN_BIND_SELLER, TARO_ENV, UPDATE_USER_SHARE_DATE
} from '../../constants/api'
import fetchNewGoodsList from "../../utils/fetchNewGoodsList";
import {autoLocation, setCity} from '../../actions/location'
import {platform} from '../../utils/platform-settting.service'
import {getHeadTop, setTempSellerId, vcmonitor} from "../../utils/tools";
import HeaderBar from '../components/header-bar/header-bar'
import {user} from "../../utils/user.service";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import Category from "../../pages/index/template/regionalCategory/component/category";
import Share from "../../components/share/share";
import './label.scss'

interface StateType {
  categoryType: any
  depth: number
  isAll: boolean
  isUser: boolean
  isActive: boolean
  categoryIdOld: number
  searchResult: Good[]
  linkUri: string
  searchText: string
  labelText: string
  searchBarTop: number
  bottomNavId: number
  subCategory: SubCategory[]
  loadStatus: any
}


type PageStateProps = {
  location: CityLocation
}

type PageDispatchProps = {
  setCity: (city: CityLocation) => void
  autoLocation: (city: CityLocation) => void
}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface CommonLabel {
  props: IProps
}

@connect(({location}) => ({
  location
}), (dispatch) => ({
  setCity(city) {
    dispatch(setCity(city))
  },
  autoLocation(city) {
    dispatch(autoLocation(city))
  }
}))

class CommonLabel extends Component {
  state: StateType = {
    categoryType: '',
    linkUri: '',
    isUser: true,
    isAll: true,
    isActive: true,
    categoryIdOld: 0,
    depth: 0,
    searchResult: [],
    subCategory: [],
    searchText: '',
    labelText: '',
    searchBarTop: 0,
    bottomNavId: 0,
    loadStatus: 'loading'
  }
  page = 1
  canMore = true
  searchType

  searchConfirm() {
    this.page = 1
    this.setState({searchResult: ''}, () => {
      this.search(this.page)
    })
  }

  async UNSAFE_componentWillMount() {
    const data = await http.post(BANNER_SEARCH_TYPE, {})
    this.searchType = +data.head_type.banner_search_type
  }

  async componentDidShow() {
    this.page = 1
    vcmonitor(this)
    Taro.showLoading({title: "加载中"})
    let bindSellerId = Taro.getStorageSync('bindSellerId') || 0;
    const headTop: any = getHeadTop()
    const searchBarTop = headTop.statusBar + headTop.top + 40
    let id = Taro.getCurrentInstance().router.params.id || ''
    let categoryType = Taro.getCurrentInstance().router.params.category || ''
    let bindSellerIds = Taro.getCurrentInstance().router.params.bindSellerId || ''
    let tempSellerIds = Taro.getCurrentInstance().router.params.tempSellerId || ''
    let scene = Taro.getCurrentInstance().router.params.scene || ''
    if (scene) {
      scene = scene.split('_')
      bindSellerIds = Number(scene[1])
      tempSellerIds = Number(scene[2])
      categoryType = scene[3]
      id = scene[4]
      const sKey = scene[5]
      if (sKey) {
        Taro.setStorageSync('sKey', sKey)
      }
    }
    const isLogin = await user.checkLogin();
    if (TARO_ENV === 'weapp' && !isLogin && (bindSellerIds || tempSellerIds)) {
      return user.jumpLogin()
    }
    const setting = await platform.getSetting();
    if (tempSellerIds) {
      setTempSellerId(tempSellerIds)
    }
    const shareParams = await user.getSellerParam(tempSellerIds)
    let link = `/common/label/label?scene=${shareParams.sellerId || 0}_${shareParams.bindSellerId || 0}_${shareParams.tempSellerId || 0}_${categoryType}_${id}_${Taro.getStorageSync('sKey' || '')}`
    if (process.env.TARO_ENV === 'h5') {
      link = window.location.origin + link
      const shareData = {
        title: platform.info.platformName,
        desc: categoryType === 1 ? '景点门票' : categoryType === 2 ? '旅游线路' : '酒店住宿',
        link,
        imgUrl: platform.info.platformLogo
      }
      h5Wx.share(shareData)
    }
    if (setting.isSellerPermanentLock) {
      if (!bindSellerId) {
        bindSellerId = bindSellerIds;
      }
    } else {
      bindSellerId = bindSellerIds;
    }
    user.bindSellerId = bindSellerId
    Taro.setStorageSync('bindSellerId', user.bindSellerId)
    if ((bindSellerIds || tempSellerIds) && process.env.DISTINGUISH_IDENTITY) {
      http.HPost(SCAN_BIND_SELLER, {temp_seller_id: tempSellerIds, refer_seller_id: bindSellerIds});
    }
    let isUser = true
    if (process.env.DISTINGUISH_IDENTITY) {
      const identityIsSeller = await http.get(IDENTITY_IS_SELLER, {})
      isUser = !identityIsSeller.isSeller
    }
    const ret = (await http.HGet(LIST_CATEGORY, {category: id, c: id, type: categoryType, pname: true})) || {}
    if (ret.data.list.some((item) => item.id === id)) {
      this.setState({isActive: false})
    }
    if (ret.data.list.length > 0) {
      this.setState({depth: ret.data.list[0].depth})
    }
    this.setState({
      isUser,
      loadStatus: '',
      searchBarTop: process.env.TARO_ENV === 'tt' ? 0 : searchBarTop,
      subCategory: ret.data.list,
      bottomNavId: id,
      isAll: ret.is_all,
      linkUri: link,
      categoryIdOld: id,
      categoryType
    })
    if (ret.data.pname) {
      Taro.setNavigationBarTitle({
        title: ret.data.pname
      })
      this.setState({labelText: ret.data.pname}, async () => {
        await this.search(this.page, id)
      })
    } else {
      if (setting && setting.platformName) {
        Taro.setNavigationBarTitle({
          title: setting.platformName
        })
      }
    }
  }

  async onReachBottom() {
    if (this.canMore) {
      this.page++
      await this.search(this.page)
    }
  }

  async search(page, id?) {
    if (this.state.searchResult && !id) {
      id = this.state.searchResult[0].category_id
    }
    Taro.showLoading({title: '加载中...'})
    const ret = await this.getSearchData(page, id);
    Taro.hideLoading()
    if (ret && ret.length > 0) {
      if (page === 1) {
        this.setState({searchResult: ret})
      } else if (page > 1) {
        const oldData = this.state.searchResult;
        this.setState({searchResult: [...oldData, ...ret]})
      }
    } else {
      this.canMore = false
      Taro.showToast({
        title: '没有更多数据了',
        icon: 'none'
      })
    }
  }

  async getGoods(page = 1, categoryId) {
    let api = CATEGORY_TOURIST_PAGE
    if (this.state.categoryType === '1') {
      api = CATEGORY_SCENIC_PAGE
    } else if (this.state.categoryType === '3') {
      api = HOTEL_PRODUCT
    }
    const dataType = this.state.categoryType == 1 ? 2 : this.state.categoryType == 2 ? 4 : 3;
    const goodsData = await fetchNewGoodsList.getGoodsList({
      module_type: "4",
      page: page,
      length: 10,
      data_type: dataType,
      key_word: this.state.searchText,
      // region_region: this.props.location.region_id,
      region_region: "",
      region_category: categoryId === 0 ? "" : categoryId,
    });
    if (goodsData && Array.isArray(goodsData)) {
      return goodsData
    } else {
      return []
    }
  }

  async getSearchData(page, id) {
    let api = CATEGORY_TOURIST_PAGE
    if (this.state.categoryType === '1') {
      api = CATEGORY_SCENIC_PAGE
    } else if (this.state.categoryType === '3') {
      api = HOTEL_PRODUCT
    }
    // 根据当前页面 categoryType 的类型, 匹配 fetchNewGoodsList<data_type> 的类型
    const dataType = this.state.categoryType == 1 ? 2 : this.state.categoryType == 2 ? 4 : 3;
    const {searchText, labelText} = this.state
    if (searchText || labelText) {
      /*const data = {
        p: page,
        areaId: this.props.location.region_id,
        k: this.state.searchText,
        c: id
      }
      const result = await http.carGet<CategoryListPageGood[]>(api, data)*/
      const result = await fetchNewGoodsList.getGoodsList({
        module_type: "4",
        page: page,
        length: 10,
        data_type: dataType,
        key_word: this.state.searchText,
        // region_region: this.props.location.region_id,
        region_region: "",
        region_category: id === 0 ? "" : id,
      });

      if (!result) {
        return false;
      }
      if (result.length < 10) {
        this.canMore = false
      }
      return result
    } else {
      Taro.showToast({
        title: '搜索词不能为空',
        icon: 'none'
      })
    }
    return false
  }

  input(value) {
    if (value) {
      this.setState({searchText: value})
    }
  }

  onShareAppMessage() {
    if (process.env.TARO_ENV !== 'tt') {
      http.post(UPDATE_USER_SHARE_DATE, {})
    }
    const {labelText, linkUri} = this.state
    return {
      imageUrl: platform.info.platformLogo,
      title: labelText,
      path: linkUri
    }
  }

  async subCategoryClick(id, depth) {
    this.page = 1
    this.canMore = true
    let data
    const {categoryIdOld, categoryType} = this.state
    if (depth === 0) { // 全部
      if (this.state.depth === 2) { // 三级
        // 没有下级
        const searchResult = await this.getGoods(this.page, categoryIdOld)
        this.setState({searchResult, isActive: true, bottomNavId: categoryIdOld})
      } else if (this.state.depth === 1) { // 有下级
        this.setState({isActive: true, bottomNavId: 0, searchResult: []})
        data = (await http.HGet(LIST_CATEGORY, {c: id, type: categoryType, bottomNavId: 0, depth})) || {}
        if (data.data.length > 0) {
          const searchResult = await this.getGoods(this.page, 0)
          if (searchResult.length > 0) {
            this.setState({searchResult, isAll: data.is_all, subCategory: data.data})
          }
        }
      }
    } else {
      if (depth === 2) { // 没有下架
        const searchResult = await this.getGoods(this.page, id)
        this.setState({isActive: false, searchResult, bottomNavId: id})
      } else { // 有下级
        data = await http.HGet(LIST_CATEGORY, {c: id, type: categoryType, depth})
        if (data && data.data.length > 0) {
          this.setState({searchResult: [], bottomNavId: id, isActive: false})
          const searchResult = await this.getGoods(this.page, id)
          if (searchResult.length > 0) {
            this.setState({searchResult, subCategory: data.data, isAll: data.is_all})
          }
        }
      }
    }
  }

  clearSearch() {
    this.setState({searchText: '', searchResult: []})
  }

  render() {
    const {searchResult, searchText, labelText, searchBarTop, bottomNavId, subCategory, isAll, isActive, isUser, linkUri, loadStatus} = this.state
    return (
      <View className='common-label-root'>
        {loadStatus !== 'loading' && <Block>
          <GzhAuth />
          {process.env.TARO_ENV !== 'tt' && <View className='head-bg' style={`height: ${searchBarTop}Px;`}>
            <HeaderBar title={labelText} />
          </View>}
          {!this.searchType && <View className='haeder'>
            <View className='search-box'>
              <AtSearchBar className='search' onConfirm={this.searchConfirm.bind(this)}
                onClear={this.clearSearch.bind(this)} onActionClick={this.searchConfirm.bind(this)}
                value={searchText} onChange={this.input.bind(this)} placeholder='搜索关键词'
              />
            </View>
          </View>}
          <View className='bottom-nav' style={`top: ${searchBarTop}px;`}>
            <View className='main'>精挑细选</View>
            <ScrollView scrollX enable-flex className='subNav'>
              <View className='nav-box'>
                {isAll && <View key={0} onClick={this.subCategoryClick.bind(this, 0, 0)}
                  className={`nav-item ${isActive ? 'active' : ''}`}
                >全部</View>}
                {subCategory.length > 0 && subCategory.map(item =>
                  <View key={item.id} onClick={this.subCategoryClick.bind(this, item.id, item.depth)}
                    className={`nav-item ${bottomNavId == item.id ? 'active' : ''}`}
                  >{item.name}</View>
                )}
              </View>
            </ScrollView>
          </View>
          {searchResult.length > 0 && <View style='height: 12.5px;' />}
          {searchResult.length > 0 && <Category data={searchResult} isUser={isUser} />}
          <View className='bottom-goods'>
            {searchResult && searchResult.length == 0 &&
            <View className='listNull'>
              <Image src={`${RESOURCE_URL}/resources/images/shopnull.png`} mode='widthFix' />
              <View className='text'>什么都没有,去看看别的吧~</View>
            </View>
            }
          </View>
          {linkUri && process.env.P_ENV !== 'lx' && <Share isUser={isUser} linkUri={linkUri} />}
        </Block>}
      </View>
    )
  }
}

export default CommonLabel as ComponentClass<PageOwnProps, PageState>
